import json
import time

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from courses.models import Course
from superuser.models import SuperUser
from cart import models, ser
# Create your views here.


class AddCart(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        添加购物车
        """
        user = request.user.id
        course_id = request.data.get('course_id')
        if not course_id:
            return Response({"msg": "课程ID不能为空", "code": 400})
        info = Course.objects.filter(id=course_id, is_del=False, status=1).first()
        if not info:
            return Response({"msg": "course_id 无效", "code": 400})
        conn = get_redis_connection('cart')
        cart_key = 'majing:cart:cart_list:' + str(user)
        course_key = 'course:' + str(course_id)
        if conn.hexists(cart_key, course_key):
            return Response({"msg": "已经购买过该商品", "code": 400})
        course_info = {
            'course_id': course_id,
            'course_name': info.name,
            'course_img': str(info.course_img),
            'price': float(info.price),
            'selected': 1,
            "add_time": int(time.time())
        }
        conn.hset(cart_key, course_key, json.dumps(course_info))
        return Response({"msg": "添加成功", "code": 200, })



class CartList(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取购物车列表
        """
        user = request.user
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        cart_list = []
        for course_id, course_info in cart_info.items():
            course_info = json.loads(course_info.decode('utf-8'))
            expire = models.CourseExplain.objects.filter(course_id=course_info['course_id'])
            if expire:
                expire_data = ser.CartSerializer(expire, many=True)
                course_info['expire'] = expire_data.data
            else:
                course_info['expire'] = [{'expire_time': 0, 'expire_text': '永久有效', 'price': course_info['price']}]
            cart_list.append(course_info)
        cart_list = sorted(cart_list, key=lambda x: x['add_time'], reverse=True)
        return Response({"msg": "获取成功", "code": 200, "data": cart_list})


class CartUpdate(APIView):
    def put(self, request):
        user = request.user
        course_id = request.data.get('course')
        if not course_id:
            return Response({"msg": "课程ID不能为空", "code": 400})
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        course_key = 'course:' + str(course_id)
        conn = get_redis_connection('cart')
        if not conn.hexists(cart_key, course_key):
            return Response({"msg": "课程不存在", "code": 400})
        course_info = conn.hget(cart_key, course_key)
        course = json.loads(course_info.decode('utf-8'))
        course['selected'] = not course['selected']
        conn.hset(cart_key, course_key, json.dumps(course))
        return Response({"msg": "修改成功", "code": 200})


class CartDelete(APIView):
    def post(self, request):
        """
        删除购物车
        """
        user = request.user
        course_id = request.data.get('course_id')
        if not course_id:
            return Response({"msg": "课程ID不能为空", "code": 400})
        course_key = 'course:' + str(course_id)
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        course_info = conn.hget(cart_key, course_key)
        if not course_info:
            return Response({"msg": "课程不存在", "code": 400})
        conn.hdel(cart_key, course_key)
        return Response({"msg": "删除成功", "code": 200})


class CartSelectAll(APIView):
    def put(self, request):
        """
        全选
        """
        user = request.user
        flag = request.data.get('flag', False)
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        cart_list = []
        for course_id, course_info in cart_info.items():
            course_info = json.loads(course_info.decode('utf-8'))
            cart_list.append(course_info)
        try:
            for course in cart_list:
                course['selected'] = flag
                course_key = 'course:' + str(course['course_id'])
                conn.hset(cart_key, course_key, json.dumps(course))
            return Response({"msg": "全选成功", "code": 200})
        except:
            return Response({"msg": "全选失败", "code": 400})


class OppositeCart(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request):
        """
        反选
        """
        user = request.data.get('user')
        info = SuperUser.objects.filter(id=user).first()
        if not info:
            return Response({"msg": "用户不存在", "code": 400})
        cart_key = 'majing:cart:cart_list:' + str(user)
        conn = get_redis_connection('cart')
        cart_info = conn.hgetall(cart_key)
        if not cart_info:
            return Response({"msg": "购物车为空", "code": 400})
        try:
            for course_id, course_info in cart_info.items():
                course_info = json.loads(course_info.decode('utf-8'))
                current_selected = bool(course_info['selected'])
                course_info['selected'] = not current_selected
                course_key = 'course:' + str(course_info['course_id'])
                conn.hset(cart_key, course_key, json.dumps(course_info))
            return Response({"msg": "反选成功", "code": 200})
        except:
            return Response({"msg": "反选失败", "code": 400})


class CartMany(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        """
        批量删除购物车
        """
        user = request.user
        course_ids = request.data.get('ids')
        if not course_ids:
            return Response({"msg": "课程ID不能为空", "code": 400})
        cart_key = 'majing:cart:cart_list:' + str(user.id)
        conn = get_redis_connection('cart')
        try:
            for course_id in list(course_ids):
                course_key = 'course:' + str(course_id)
                conn.hdel(cart_key, course_key)
                return Response({"msg": "删除成功", "code": 200})
        except:
            return Response({"msg": "删除失败", "code": 400})







